<?php


class LessonService extends Service
{
  /**
   * @param string $className
   * @return LessonService
   */
  public static function instance($className = __CLASS__)
  {
    return parent::instance($className);
  }

  /**
   * 获取课程列表
   * @param int $pageSize 分页大小
   * @param bool $with 是否关联
   * @param bool $showAll 是否显示搜游
   * @param int $user_id 创建者
   * @param string $keywords 搜索
   * @return array
   */
  public function getList($pageSize = 20, $with = true, $showAll = false, $user_id = 0, $keywords = '')
  {
    $criteria = new CDbCriteria();
    //显示某用户的
    if ($user_id > 0) {
      $criteria->condition = 'user_id = :user_id';
      $criteria->params = array(':user_id' => $user_id);
    }
    //是否显示所有
    if (!$showAll) {
      $criteria->addCondition('lesson.state = 1');
    }
    //关键字
    if (!empty($keywords)) {
      $criteria->addSearchCondition('lesson.name', $keywords);
    }
    //关联
    if ($with) {
      $criteria->with = array(
          'articles',
          'user'
      );
    }
    $criteria->order = 'lesson.hits desc,lesson.created_at';
    $count = Lesson::model()->count($criteria);
    $pages = new CPagination($count);
    $pages->pageSize = $pageSize;
    $pages->applyLimit($criteria);
    $criteria->offset = $pages->currentPage * $pages->pageSize;
    $list = Lesson::model()->findAll($criteria);
    return array(
        'list' => $list,
        'pages' => $pages
    );
  }

  /**
   * 添加/编辑课程
   * @param array $data 课程数据
   * @param int $user_id 创建者ID(编辑时凭证)
   * @return array|bool|string
   */
  public function post($data = array(), $user_id = 0)
  {
    if (empty($data['lesson_id'])) {
      $lesson = new Lesson();
    } else {
      $lesson = Lesson::model()->findByPk($data['lesson_id']);
      if ($lesson->user_id != $user_id) {
        return '对不起，该课程不是你创建的!';
      }
    }
    $lesson->attributes = $data;
    return $lesson->save() ? true : $lesson->errors;
  }

  /**
   * 设置课程状态
   * @param array $list
   * @param int $state
   * @return bool
   */
  public function setState($list = array(), $state = 0)
  {
    $criteria = new CDbCriteria();
    $criteria->addInCondition('lesson_id',$list);
    return Lesson::model()->updateAll(array('state'=>$state),$criteria)?true:false;
  }
} 